package com.song.druid.aop;

import com.song.druid.annotation.SensitiveData;
import com.song.druid.util.SensitiveUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 方法执行前对敏感数据加密
 */
@Slf4j
//@Aspect
//@Component
public class EncryptAspect {
    /**
     * 切点方法
     */
    @Pointcut("(@annotation(com.song.druid.annotation.EnableSensitive))")
    private void pointCut(){}

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint){
        try {
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                if (arg instanceof List){
                    List list = (List) arg;
                    encryptList(list);
                    continue;
                }
                encryptObj(arg);
            }
        }catch (Exception e) {
            log.error("敏感数据加密失败！");
        }
    }

    public void encryptList(List objList) throws IllegalAccessException {
        for (Object obj : objList) {
            encryptObj(obj);
        }
    }

    public void encryptObj(Object obj) throws IllegalAccessException {
        Class<?> aClass = obj.getClass();
        SensitiveData sensitiveData = AnnotationUtils.findAnnotation(aClass, SensitiveData.class);
        if (ObjectUtils.isNotEmpty(sensitiveData)){
            Field[] fields = aClass.getDeclaredFields();
            SensitiveUtil.encrypt(fields, obj);
        }
    }
}
